﻿using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Net;
using System.Xml;

public partial class sendsms : System.Web.UI.Page
{
    static int userid;
    static string message;
    int countcontact = 0;
    const char Delimiter = '-';
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt = SqlHelper.ExecuteDatatable(GlobalVariable.con, CommandType.Text, "select (FromNumber+' '+' '+Description) as DTF,FromNumber,Description from tbl_FromNumbers");
            RBL_FromNumbers.DataSource = dt;
            RBL_FromNumbers.DataTextField = "DTF";
            RBL_FromNumbers.DataValueField = "FromNumber";
            RBL_FromNumbers.DataBind();
            txtDate.Text = System.DateTime.Now.ToShortDateString();
            if (dt.Rows.Count > 0)
            {
                RBL_FromNumbers.SelectedIndex = 0;
            }

            if (Session["smsgrpid"] != null)
            {
                RadioButtonList1.SelectedIndex = 0;
            }
            else
            {
                RadioButtonList1.SelectedIndex = 1;
            }
            if (RadioButtonList1.SelectedItem.Text == "Single Number")
            {
                lbtnSubG.Visible = false;
                pnlSubGroup.Visible = false;
                pnlSingleNumber.Visible = true;
            }
            else
            {
                if (RadioButtonList1.SelectedItem.Text == "Send to entire group")
                {
                    lbtnSubG.Visible = true;
                    pnlSubGroup.Visible = true;
                    pnlSingleNumber.Visible = false;
                    //DataSet ds2 = SqlHelper.ExecuteDataset(GlobalVariable.con, CommandType.Text, "select groupid,groupname from tbl_group where userid = '" + Convert.ToInt32(lbluid.Text) + "'");
                    DataSet ds2 = SqlHelper.ExecuteDataset(GlobalVariable.con, CommandType.Text, "select groupid,groupname from tbl_group where GroupName!='Opt Outs'");
                    DataTable dt2 = ds2.Tables[0];
                    ddlSubGroup.DataSource = dt2;
                    ddlSubGroup.DataTextField = "groupname";
                    ddlSubGroup.DataValueField = "groupid";
                    ddlSubGroup.DataBind();
                    string a = "";
                    if (Session["smsgrpid"] != null)
                    {
                        a = Session["smsgrpid"].ToString();
                    }
                    else
                    {
                        a = ddlSubGroup.SelectedValue;
                    }
                    if (a != "")
                    {
                        DataSet ds1 = SqlHelper.ExecuteDataset(GlobalVariable.con, CommandType.Text, "select MobileNumber,FirstName,LastName from tbl_groupcontacts where groupid = '" + ddlSubGroup.SelectedValue + "'");
                        DataTable dt1 = ds1.Tables[0];
                        grdGroupContacts.DataSource = dt1;
                        grdGroupContacts.DataBind();
                        lblmergelist.Visible = true;
                        ddlmailmergelist.Visible = true;
                        DataTable coldt = SqlHelper.ExecuteDatatable(GlobalVariable.con, CommandType.Text, "select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tbl_groupcontacts'");
                        foreach (DataRow row in coldt.Rows)
                        {
                            string colname = row["COLUMN_NAME"].ToString();
                            if (colname == "GroupId")
                            {
                                row.Delete();
                            }
                            if (colname == "currentDT")
                            {
                                row.Delete();
                            }
                            if (colname == "ContactId")
                            {
                                row.Delete();
                            }
                        }
                        ddlmailmergelist.DataSource = coldt;
                        ddlmailmergelist.DataTextField = "COLUMN_NAME";
                        ddlmailmergelist.DataValueField = "COLUMN_NAME";
                        ddlmailmergelist.DataBind();
                        ddlmailmergelist.Items.Insert(0, "--Select--");
                        object subgroupcontacts = SqlHelper.ExecuteScalar(GlobalVariable.con, CommandType.Text, "select count(MobileNumber) from tbl_groupcontacts where groupid = '" + ddlSubGroup.SelectedValue + "'");
                        lbtnSubG.Text = subgroupcontacts + " " + "Contacts";
                        foreach (GridViewRow grdrow in grdGroupContacts.Rows)
                        {
                            CheckBox ContactChecked1 = (CheckBox)grdrow.Cells[0].FindControl("ChkCkeck");
                            if (ContactChecked1.Checked == true)
                            {
                                countcontact++;
                            }
                        }
                        cc.Text = countcontact.ToString();
                    }
                    else
                    {
                        lbtnSubG.Text = "0 Contacts";
                    }
                }
            }
            if (Session["smsgrpid"] != null)
            {
                Session["smsgrpid"] = null;
            }
            object tweakid = SqlHelper.ExecuteScalar(GlobalVariable.con,CommandType.Text,"select tweakid from tbl_Tweak");
            if (tweakid != null)
            {
                object tweakvalue = SqlHelper.ExecuteScalar(GlobalVariable.con, CommandType.Text, "select tweakvalue from tbl_Tweak");
                int tvalue = Convert.ToInt32(tweakvalue);
                double twkvalue = (double)tvalue / 1000;
                lblTweakValue.Text = twkvalue.ToString();
            }
            else
            {
                lblTweakValue.Text = "0";
            }
        }
    }
    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (RadioButtonList1.SelectedItem.Text == "Single Number")
        {
            lbtnSubG.Visible = false;
            //lbtnMGC.Visible = false;
            pnlSubGroup.Visible = false;
            pnlSingleNumber.Visible = true;
            lblmergelist.Visible = false;
            ddlmailmergelist.Visible = false;
        }
        else
        {
            if (RadioButtonList1.SelectedItem.Text == "Send to entire group")
            {
                lbtnSubG.Visible = true;
                //lbtnMGC.Visible = false;
                pnlSubGroup.Visible = true;
                pnlSingleNumber.Visible = false;
                //DataSet ds = SqlHelper.ExecuteDataset(GlobalVariable.con, CommandType.Text, "select groupid,groupname from tbl_group where userid = '" + Convert.ToInt32(lbluid.Text) + "'");
                DataSet ds = SqlHelper.ExecuteDataset(GlobalVariable.con, CommandType.Text, "select groupid,groupname from tbl_group");                
                DataTable dt = ds.Tables[0];
                ddlSubGroup.DataSource = dt;
                ddlSubGroup.DataTextField = "groupname";
                ddlSubGroup.DataValueField = "groupid";
                ddlSubGroup.DataBind();
                string a = ddlSubGroup.SelectedValue;
                if (a != "")
                {
                    DataSet ds1 = SqlHelper.ExecuteDataset(GlobalVariable.con, CommandType.Text, "select MobileNumber,FirstName,LastName from tbl_groupcontacts where groupid = '" + ddlSubGroup.SelectedValue + "'");
                    DataTable dt1 = ds1.Tables[0];
                    grdGroupContacts.DataSource = dt1;
                    grdGroupContacts.DataBind();
                    lblmergelist.Visible = true;
                    ddlmailmergelist.Visible = true;
                    DataTable coldt = SqlHelper.ExecuteDatatable(GlobalVariable.con, CommandType.Text, "select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tbl_groupcontacts'");
                    foreach (DataRow row in coldt.Rows)
                    {
                        string colname = row["COLUMN_NAME"].ToString();
                        if (colname == "GroupId")
                        {
                            row.Delete();
                        }
                        if (colname == "currentDT")
                        {
                            row.Delete();
                        }
                        if (colname == "ContactId")
                        {
                            row.Delete();
                        }
                    }
                    ddlmailmergelist.DataSource = coldt;
                    ddlmailmergelist.DataTextField = "COLUMN_NAME";
                    ddlmailmergelist.DataValueField = "COLUMN_NAME";
                    ddlmailmergelist.DataBind();
                    ddlmailmergelist.Items.Insert(0, "--Select--");
                    object subgroupcontacts = SqlHelper.ExecuteScalar(GlobalVariable.con, CommandType.Text, "select count(MobileNumber) from tbl_groupcontacts where groupid = '" + ddlSubGroup.SelectedValue + "'");
                    lbtnSubG.Text = subgroupcontacts + " " + "Contacts";
                    foreach (GridViewRow grdrow in grdGroupContacts.Rows)
                    {
                        CheckBox ContactChecked1 = (CheckBox)grdrow.Cells[0].FindControl("ChkCkeck");
                        if (ContactChecked1.Checked == true)
                        {
                            countcontact++;
                        }
                    }
                    cc.Text = countcontact.ToString();
                }
                else
                {
                    lbtnSubG.Text = "0 Contacts";
                }
            }
        }
    }
    private void sendsms1()
    {
        if (RadioButtonList1.SelectedItem.Text == "Single Number")
        {
            if (txtSingleNumber.Text != "" && txtSingleNumber.Text.Length >= 10)
            {
                DateTime zonetime = getClientTime(DateTime.UtcNow.ToString(), ddlTimeZone.SelectedValue);
                DateTime ScheduleDateTime = Convert.ToDateTime(txtDate.Text + " " + DropDownListHour.SelectedValue + ":" + DropDownListMinute.SelectedValue + " " + ddlAMPM.SelectedValue);
                if (ScheduleDateTime > zonetime)
                {
                    //SqlHelper.ExecuteNonQuery(GlobalVariable.con, CommandType.Text, "insert into tbl_SentMessages (MsgTo,MsgText,MsgStatus,UserId,groupid,SentDateTime,ScheduleDateTime,smsDeliveryTime,TimeZone,Frequency,TillDate) values('" + txtSingleNumber.Text.Trim() + "','" + message + "','" + GlobalVariable.MsgStatus.scheduled.ToString() + "','" + Convert.ToInt32(lbluid.Text) + "','" + ddlSubGroup.SelectedValue + "','" + DateTime.Now + "','" + ScheduleDateTime + "',null,'" + ddlTimeZone.SelectedValue + "','" + ddFrequency.SelectedValue + "','" + Convert.ToDateTime(txtTillDate.Text) + "')");
                    SqlHelper.ExecuteNonQuery(GlobalVariable.con, CommandType.Text, "insert into tbl_SentMessages (MsgFrom,MsgTo,MsgText,MsgStatus,UserId,GroupId,SentDateTime,ScheduleDateTime,smsDeliveryTime,TimeZone) values('" +
                        RBL_FromNumbers.SelectedValue + "','" + txtSingleNumber.Text.Trim() + "','" + message + "','" + GlobalVariable.MsgStatus.scheduled.ToString() + "','" + null + "','" + ddlSubGroup.SelectedValue + "','" + DateTime.Now + "','" + ScheduleDateTime + "',null,'" + ddlTimeZone.SelectedValue + "')");
                    sentsinglemsgs();
                }
                else
                {
                    string SelectGroup = "Please select future time";
                    Page.Controls.Add(new LiteralControl("<script language='javascript'> window.alert('" + SelectGroup + "')</script>"));
                }

            }
            else
            {
                string SelectGroup = " Please specify a correct number to send message";
                Page.Controls.Add(new LiteralControl("<script language='javascript'> window.alert('" + SelectGroup + "')</script>"));
            }
        }
        else
        {
            string grouptext = "";
            foreach (GridViewRow grdrow in grdGroupContacts.Rows)
            {
                CheckBox ContactChecked = (CheckBox)grdrow.Cells[0].FindControl("ChkCkeck");
                Label lblNumber = (Label)grdrow.Cells[1].FindControl("lblNumber");
                DataTable coldt = SqlHelper.ExecuteDatatable(GlobalVariable.con, CommandType.Text, "select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tbl_groupcontacts'");
                foreach (DataRow row in coldt.Rows)
                {
                    string colname = row["COLUMN_NAME"].ToString();
                    if (colname == "GroupId")
                    {
                        row.Delete();
                    }
                    if (colname == "currentDT")
                    {
                        row.Delete();
                    }
                    if (colname == "ContactId")
                    {
                        row.Delete();
                    }
                    string customtext = "#" + colname + "#";
                    if (message.Contains(customtext))
                    {
                        object obj = SqlHelper.ExecuteScalar(GlobalVariable.con, CommandType.Text, "select " + colname + " from tbl_groupcontacts where MobileNumber='" + lblNumber.Text + "' and GroupId=" + ddlSubGroup.SelectedValue + "");
                        string newobj = obj.ToString();
                        if (grouptext == "")
                        {
                            grouptext = CreateSMS(message, customtext, newobj);
                        }
                        else
                        {
                            grouptext = CreateSMS(grouptext, customtext, newobj);
                        }
                    }
                }
                if (grouptext == "")
                {
                    grouptext = message;
                }
               
                if (ContactChecked.Checked == true)
                {
                    DateTime zonetime = getClientTime(DateTime.UtcNow.ToString(), ddlTimeZone.SelectedValue);
                    DateTime ScheduleDateTime = Convert.ToDateTime(txtDate.Text + " " + DropDownListHour.SelectedValue + ":" + DropDownListMinute.SelectedValue + " " + ddlAMPM.SelectedValue);
                    
                        if (ScheduleDateTime > zonetime)
                        {
                            //SqlHelper.ExecuteNonQuery(GlobalVariable.con, CommandType.Text, "insert into tbl_SentMessages (MsgTo,MsgText,MsgStatus,UserId,GroupId,SentDateTime,ScheduleDateTime,smsDeliveryTime,TimeZone,Frequency,TillDate) values('" + lblNumber.Text + "','" + grouptext + "','" + GlobalVariable.MsgStatus.scheduled.ToString() + "','" + Convert.ToInt32(lbluid.Text) + "','" + ddlSubGroup.SelectedValue + "','" + DateTime.Now + "','" + ScheduleDateTime + "',null,'" + ddlTimeZone.SelectedValue + "','" + ddFrequency.SelectedValue + "','" + Convert.ToDateTime(txtTillDate.Text) + "')");
                            SqlHelper.ExecuteNonQuery(GlobalVariable.con, CommandType.Text, "insert into tbl_SentMessages (MsgFrom,MsgTo,MsgText,MsgStatus,UserId,GroupId,SentDateTime,ScheduleDateTime,smsDeliveryTime,TimeZone) values('" + RBL_FromNumbers.SelectedValue + "','" + lblNumber.Text + "','" + grouptext + "','" + GlobalVariable.MsgStatus.scheduled.ToString() + "','" + null + "','" + ddlSubGroup.SelectedValue + "','" + DateTime.Now + "','" + ScheduleDateTime + "',null,'" + ddlTimeZone.SelectedValue + "')");
                            countcontact++;
                        }
                        else
                        {
                            string SelectGroup = " Please select future time";
                            Page.Controls.Add(new LiteralControl("<script language='javascript'> window.alert('" + SelectGroup + "')</script>"));
                        }
                   
                   
                }
                grouptext = "";
            }

            txtmessage.Text = "";
           
            string SelectGroup1 = "" + countcontact + " messages scheduled to " + ddlSubGroup.SelectedItem.Text + " Group contacts";
            Page.Controls.Add(new LiteralControl("<script language='javascript'> window.alert('" + SelectGroup1 + "')</script>"));
            
        }
    }
    private void sentsinglemsgs()
    {
        countcontact = 1;

        string SelectGroup = "" + countcontact + " message scheduled to " + txtSingleNumber.Text.Trim() + " number";
        Page.Controls.Add(new LiteralControl("<script language='javascript'> window.alert('" + SelectGroup + "')</script>"));


        txtmessage.Text = "";

        txtSingleNumber.Text = "";
    }
    public int msgcount(int uid, int msgcount)
    {
        object msgsleft = SqlHelper.ExecuteScalar(GlobalVariable.con, CommandType.Text, "select MsgsLeft from tbl_user where userid = '" + uid + "'");
        int abc = Convert.ToInt32(msgsleft.ToString());
        int leftmsgss = abc - msgcount;
        SqlHelper.ExecuteNonQuery(GlobalVariable.con, CommandType.Text, "update tbl_user set MsgsLeft = '" + leftmsgss + "' where userid = '" + uid + "'");
        return leftmsgss;

    }
    protected void chk_CheckedChanged(object sender, EventArgs e)
    {
        if (chk.Checked == false)
        {
            foreach (GridViewRow grdrow in grdGroupContacts.Rows)
            {
                CheckBox ContactChecked = (CheckBox)grdrow.Cells[0].FindControl("ChkCkeck");
                ContactChecked.Checked = false;
                cc.Text = "0";
                lblcheckall.Text = "Check All Contacts";
            }
        }
        else
        {
            foreach (GridViewRow grdrow in grdGroupContacts.Rows)
            {
                CheckBox ContactChecked1 = (CheckBox)grdrow.Cells[0].FindControl("ChkCkeck");
                ContactChecked1.Checked = true;
                lblcheckall.Text = "UnCheck All Contacts";
                countcontact++;
            }
            cc.Text = countcontact.ToString();
        }
    }
    protected void ChkCkeck_CheckedChanged(object sender, EventArgs e)
    {
        foreach (GridViewRow grdrow in grdGroupContacts.Rows)
        {
            CheckBox ContactChecked1 = (CheckBox)grdrow.Cells[0].FindControl("ChkCkeck");
            if (ContactChecked1.Checked == true)
            {
                countcontact++;
            }
        }
        cc.Text = countcontact.ToString();
    }
    protected void ddlSubGroup_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataSet ds1 = SqlHelper.ExecuteDataset(GlobalVariable.con, CommandType.Text, "select MobileNumber,FirstName,LastName from tbl_groupcontacts where groupid = '" + ddlSubGroup.SelectedValue + "'");
        object subgroupcontacts = SqlHelper.ExecuteScalar(GlobalVariable.con, CommandType.Text, "select count(MobileNumber) from tbl_groupcontacts where groupid = '" + ddlSubGroup.SelectedValue + "'");
        lbtnSubG.Text = subgroupcontacts + " " + "Contacts";
        DataTable dt1 = ds1.Tables[0];
        grdGroupContacts.DataSource = dt1;
        grdGroupContacts.DataBind();
    }
    protected void RBL_sendsms_SelectedIndexChanged(object sender, EventArgs e)
    {
        //if (RBL_sendsms.SelectedItem.Text != "Send Message Now")
        //{
            txtDate.Text = System.DateTime.Now.ToShortDateString();
            Panel12.Visible = true;
        //}
        //else
        //{
        //    Panel12.Visible = false;
        //}
    }
    public static DateTime getClientTime(string date, object O)
    {
        if (O != null)
        {
            string Temp = O.ToString().Trim();
            if (!Temp.Contains("+") && !Temp.Contains("-"))
            {
                Temp = Temp.Insert(0, "+");
            }

            ReadOnlyCollection<TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones();
            DateTime startTime = DateTime.Parse(date);
            DateTime _now = DateTime.Parse(date);
            foreach (TimeZoneInfo timeZoneInfo in timeZones)
            {
                if (timeZoneInfo.ToString().Contains(Temp))
                {
                    //Response.Write(timeZoneInfo.ToString());
                    //string _timeZoneId = "Pacific Standard Time";
                    TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById(timeZoneInfo.Id);
                    _now = TimeZoneInfo.ConvertTime(startTime, TimeZoneInfo.Utc, tst);

                    break;
                }
            }
            return _now;
        }
        else
            return DateTime.Parse(date);
    }
    protected void btnSend_Click(object sender, ImageClickEventArgs e)
    {
        if (txtTweakSpeed.Text != "")
        {
            object twkid = SqlHelper.ExecuteScalar(GlobalVariable.con, CommandType.Text, "select tweakid from tbl_Tweak");
            decimal tweakvalue = Convert.ToDecimal(txtTweakSpeed.Text) * 1000;
            if (twkid == null)
            {
                SqlHelper.ExecuteNonQuery(GlobalVariable.con, CommandType.Text, "insert into tbl_Tweak (tweakvalue,userid) values(" + Convert.ToInt32(tweakvalue) + "," + userid + ")");
            }
            else
            {
                SqlHelper.ExecuteNonQuery(GlobalVariable.con, CommandType.Text, "update tbl_Tweak set tweakvalue=" + Convert.ToInt32(tweakvalue) + " where userid =" + userid + "");
            }
        }
        message = txtmessage.Text;
        sendsms1();
    }
    public string CreateSMS(string OleSMS, string oldField, string Field)
    {
        string SMS = OleSMS.Trim();
        if (SMS.Contains(oldField))
        {
            SMS = SMS.Replace(oldField, Field);
        }
        return SMS;
    }

    protected void btnAddNumber_Click(object sender, EventArgs e)
    {
        object nmbr = SqlHelper.ExecuteScalar(GlobalVariable.con, CommandType.Text, "select NumberId from tbl_FromNumbers where fromNumber='" + txtAddNumber.Text.Trim() + "'");
        if (nmbr == null)
        {
            string url = "https://secure.ifbyphone.com/ibp_api.php?api_key=e4676a825907ad87aba2c6ac4c6ec3905765ca82&action=sms.register_number&number=" + txtAddNumber.Text.Trim() + "";
            System.Net.HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string abc = reader.ReadToEnd();
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(abc);
            XmlNodeList result = xmlDoc.GetElementsByTagName("result");
            XmlNodeList result_description = xmlDoc.GetElementsByTagName("result_description");
            string rslt = result[0].InnerText;
            if (rslt == "success")
            {
                SqlHelper.ExecuteNonQuery(GlobalVariable.con, CommandType.Text, "insert into tbl_FromNumbers (FromNumber,Description) values('" + txtAddNumber.Text.Trim() + "','" + txtDescription.Text + "')");
                DataTable dt = SqlHelper.ExecuteDatatable(GlobalVariable.con, CommandType.Text, "select NumberId,FromNumber from tbl_FromNumbers");
                RBL_FromNumbers.DataSource = dt;
                RBL_FromNumbers.DataTextField = "FromNumber";
                RBL_FromNumbers.DataValueField = "NumberId";
                RBL_FromNumbers.DataBind();

                if (dt.Rows.Count > 0)
                {
                    RBL_FromNumbers.SelectedIndex = 0;
                }
                string SelectGroup1 = result_description[0].InnerText;
                Page.Controls.Add(new LiteralControl("<script language='javascript'> window.alert('" + SelectGroup1 + "')</script>"));
                lblmsg.Text = SelectGroup1;
                //lbtnAddNumber_ModalPopupExtender.OkControlID=
            }
            else
            {
                string SelectGroup1 = result_description[0].InnerText;
                Page.Controls.Add(new LiteralControl("<script language='javascript'> window.alert('" + SelectGroup1 + "')</script>"));
                lblmsg.Text = SelectGroup1;
            }
        }
        else
        {
            lblmsg.Text = "This number already exists in our database.";
        }
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Response.Redirect(Request.Url.AbsoluteUri);
    }
    protected void ddlTimeZone_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlTimeZone.SelectedIndex > 0)
        {
            DateTime zonetime = getClientTime(DateTime.UtcNow.ToString(), ddlTimeZone.SelectedValue);
            zonetime = zonetime.AddMinutes(5);
            String time = zonetime.ToString("HH':'mm tt");
            string[] hrs = time.Split(':');
            DropDownListHour.SelectedValue = hrs.GetValue(0).ToString();
            string mnte = hrs.GetValue(1).ToString();
            string[] aa = mnte.Split(' ');
            DropDownListMinute.SelectedValue = aa.GetValue(0).ToString();
            ddlAMPM.SelectedValue = aa.GetValue(1).ToString();

        }
        else
        {
            if (ddlTimeZone.SelectedIndex == 0)
            {
                DropDownListHour.SelectedIndex = 0;
                DropDownListMinute.SelectedIndex = 0;
            }
        }
    }
}
